'''
任务进度相关的API路由
'''
from flask import Blueprint, request, jsonify, g, current_app
from psycopg2.extras import RealDictCursor
from utils.helpers import check_task_dependencies, update_task_progress

# 创建蓝图
progress_bp = Blueprint('progress', __name__, url_prefix='/api')

# 16. 更新任务进度
@progress_bp.route('/tasks/<int:task_id>/progress', methods=['POST'])
def update_progress(task_id):
    data = request.get_json()
    
    if not data or 'progress' not in data:
        return jsonify({
            'status': 'error',
            'message': '进度值不能为空'
        }), 400
    
    progress = float(data['progress'])
    status = data.get('status')
    comments = data.get('comments', '')
    logged_by = data.get('logged_by', 'user')
    time_spent = data.get('time_spent', 0)
    
    # 检查进度值是否合法
    if progress < 0 or progress > 100:
        return jsonify({
            'status': 'error',
            'message': '进度值必须在0-100之间'
        }), 400
    
    # 更新任务进度
    success = update_task_progress(task_id, progress, status, comments, logged_by, time_spent)
    
    if success:
        # 如果进度为100%且未指定状态，则将状态更新为已完成
        if progress == 100 and not status:
            update_task_progress(task_id, 100, 'completed', '任务已完成', logged_by, time_spent)
            
            # 检查依赖于此任务的其他任务是否可以执行
            conn = g.db
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            
            cursor.execute('''
            SELECT td.dependent_task_id
            FROM task_dependencies td 
            JOIN sub_tasks st ON td.dependent_task_id = st.id
            WHERE td.dependency_task_id = %s AND st.status = 'blocked'
            ''', (task_id,))
            
            blocked_tasks = cursor.fetchall()
            
            for blocked_task in blocked_tasks:
                # 检查此任务的所有依赖是否都已完成
                if check_task_dependencies(blocked_task['dependent_task_id']):
                    cursor.execute('SELECT * FROM sub_tasks WHERE id = %s', (blocked_task['dependent_task_id'],))
                    task = cursor.fetchone()
                    
                    update_task_progress(
                        task['id'], 
                        task['progress'], 
                        'pending', 
                        '依赖任务已完成，任务可以执行'
                    )
        
        return jsonify({
            'status': 'success',
            'message': '任务进度已更新'
        })
    else:
        return jsonify({
            'status': 'error',
            'message': '任务不存在或更新失败'
        }), 404

# 17. 获取任务进度历史
@progress_bp.route('/tasks/<int:task_id>/progress/history', methods=['GET'])
def get_progress_history(task_id):
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute('''
    SELECT * FROM task_progress_logs
    WHERE sub_task_id = %s
    ORDER BY log_time DESC
    ''', (task_id,))
    
    logs = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': logs
    })

# 18. 获取阻塞的任务列表
@progress_bp.route('/tasks/blocked', methods=['GET'])
def get_blocked_tasks():
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 查询被阻塞的任务
    cursor.execute('''
    SELECT 
        st.id, st.title, st.description, st.status,
        mt.id as main_task_id, mt.title as main_task_title,
        p.id as project_id, p.name as project_name
    FROM sub_tasks st
    JOIN task_breakdown_versions tbv ON st.breakdown_version_id = tbv.id
    JOIN main_tasks mt ON tbv.main_task_id = mt.id
    JOIN projects p ON mt.project_id = p.id
    WHERE 
        st.status = 'blocked'
    ORDER BY st.id
    ''')
    
    tasks = cursor.fetchall()
    
    return jsonify({
        'status': 'success',
        'data': tasks
    }) 